package com.chem.lems.serves.impl;

import com.chem.lems.constans.BackupConstants;
import com.chem.lems.constans.ResultCodeConstant;
import com.chem.lems.serves.BackupServices;
import com.chem.lems.utils.FileUtils;
import com.chem.lems.utils.MySqlBackupRestoreUtils;
import com.chem.lems.utils.ResultUtil;
import com.chem.lems.vo.BackupBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class BackupServicesImpl implements BackupServices {
    /**
     * 查询备份列表
     *
     * @return
     */
    @Override
    public ResultUtil queryBackup() {
        List<Map<String, String>> backupRecords = new ArrayList<>();
        File restoreFolderFile = new File(BackupConstants.SFOLDER_NAME);
        if (restoreFolderFile.exists()) {
            for (File file : restoreFolderFile.listFiles()) {
                if (file.exists()) {
                    for (File files : file.listFiles()) {
                        Map<String, String> backup = new HashMap<>();
                        long time = files.lastModified();
                        Calendar cal = Calendar.getInstance();
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        cal.setTimeInMillis(time);
                        backup.put("title", files.getName());
                        backup.put("time", formatter.format(cal.getTime()));
                        backup.put("path", files.getPath().concat(".sql"));
                        backupRecords.add(backup);
                    }
                } else {
                    Map<String, String> backup = new HashMap<>();
                    long time = file.lastModified();
                    Calendar cal = Calendar.getInstance();
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    cal.setTimeInMillis(time);
                    backup.put("title", file.getName());
                    backup.put("time", formatter.format(cal.getTime()));
                    backup.put("path", file.getPath().concat(".sql"));
                    backupRecords.add(backup);
                }
            }
        }
        // 按时间戳排序，新备份在前面
        backupRecords.sort((o1, o2) -> o2.get("title").compareTo(o1.get("title")));
        return new ResultUtil(ResultCodeConstant.SUCCESS, "获取数据备份列表成功！", backupRecords);
    }

    /**
     * 数据库备份
     *
     * @param backupBO
     * @return
     */
    @Override
    public ResultUtil backup(BackupBO backupBO) {
        String host = BackupConstants.HOST;
        String port = BackupConstants.PORT;
        String userName = BackupConstants.USER_NAME;
        String password = BackupConstants.PASSWORD;
        String database = BackupConstants.DATABASE;
        String backupFolderPath = BackupConstants.BACKUP_FOLDER + backupBO.getTitle() + File.separator;
        String fileName = backupBO.getTitle();
        try {
            boolean success = MySqlBackupRestoreUtils.backup(host, port,userName, password, backupFolderPath, fileName, database);
            if (!success) {
                log.info("数据备份失败");
                return new ResultUtil(ResultCodeConstant.FAIL, "数据备份失败！");
            }
        } catch (Exception e) {
            log.debug(e.toString());
            return new ResultUtil(ResultCodeConstant.FAIL, "数据备份异常！");
        }
        return new ResultUtil(ResultCodeConstant.SUCCESS, "数据备份成功！");
    }

    /**
     * 还原数据库
     *
     * @param backupBO
     * @return
     */
    @Override
    public ResultUtil restore(BackupBO backupBO) {
        String separator = File.separator;
        String host = BackupConstants.HOST;
        String port = BackupConstants.PORT;
        String userName = BackupConstants.USER_NAME;
        String password = BackupConstants.PASSWORD;
        String database = BackupConstants.DATABASE;
        String restoreFilePath = backupBO.getPath().replace(".sql", "");
        try {
            boolean result = MySqlBackupRestoreUtils.restore(restoreFilePath, host,port, userName, password, database);
            if (!result) {
                return new ResultUtil(ResultCodeConstant.FAIL, "数据还原失败！");
            }
        } catch (Exception e) {
            log.debug(e.toString());
            return new ResultUtil(ResultCodeConstant.FAIL, "数据还原失败！");
        }
        return new ResultUtil(ResultCodeConstant.SUCCESS, "数据还原成功！");
    }


    /**
     * 删除数据库备份
     *
     * @param title
     * @param path
     * @return
     */
    @Override
    public ResultUtil delBackup(String title, String path) {
        String separator = File.separator;
        String restoreFilePath = BackupConstants.SFOLDER_NAME.concat(separator).concat(path).concat(separator).concat(title);
        try {
            FileUtils.deleteFile(new File(restoreFilePath));
        } catch (Exception e) {
            log.debug(e.toString());
            return new ResultUtil(ResultCodeConstant.FAIL, "删除数据库备份失败！");
        }
        return new ResultUtil(ResultCodeConstant.SUCCESS, "数据库备份删除成功！");
    }

    @Override
    public ResultUtil getBackupDate() {
        List<Map<String, String>> backupRecords = new ArrayList<>();
        File restoreFolderFile = new File(BackupConstants.SFOLDER_NAME);
        if (restoreFolderFile.exists()) {
            for (File file : restoreFolderFile.listFiles()) {
                if (file.exists()) {
                    for (File files : file.listFiles()) {
                        Map<String, String> backup = new HashMap<>();
                        long time = files.lastModified();
                        Calendar cal = Calendar.getInstance();
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                        cal.setTimeInMillis(time);
                        backup.put("content", files.getName());
                        backup.put("date", formatter.format(cal.getTime()));
                        backupRecords.add(backup);
                    }
                } else {
                    Map<String, String> backup = new HashMap<>();
                    long time = file.lastModified();
                    Calendar cal = Calendar.getInstance();
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    cal.setTimeInMillis(time);
                    backup.put("content", file.getName());
                    backup.put("date", formatter.format(cal.getTime()));
                    backupRecords.add(backup);
                }
            }
        }
        // 按时间戳排序，新备份在前面
        return new ResultUtil(ResultCodeConstant.SUCCESS, "获取数据备份列表成功！", backupRecords);
    }
}

